package utils;

import dao.ActiveMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import pojo.Active;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

//sqkSessionFactory --> sqlSession
public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;
    static {
        String resource = "mybatis-config.xml";
        try {
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //既然有了 SqlSessionFactory，顾名思义，我们可以从中获得 SqlSession 的实例。SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。
    // 你可以通过 SqlSession 实例来直接执行已映射的 SQL 语句。例如：
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession(true);
    }
    public static String getYanZheng(){
        SqlSession session = MybatisUtils.getSqlSession();
        ActiveMapper mapper = session.getMapper(ActiveMapper.class);
        List<Active> actives = mapper.queryAll();
        session.close();
        return actives.get(0).getName();
    }
}
